package com.tanhua.dubbo.api;

import com.tanhua.dubbo.util.IdWorker;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private TimeLineService timeLineService;

    @Autowired
    private IdWorker idWorker;

    //发送动态
    @Override
    public String publish(Movement movement) {
        //1.保存动态详情
        //设置pid
        movement.setPid(idWorker.getNextId("movement"));
        //设置时间
        movement.setCreated(System.currentTimeMillis());
        //保存属性
        mongoTemplate.save(movement);
        timeLineService.saveTimeLine(movement);
        return movement.getId().toHexString();
    }

    //查询动态返回总记录数
    @Override
    public PageResult<Movement> findPageByUserId(Long userId, Integer page, Integer pageSize) {
        //1.封装查询条件 根据用户id查询
        Query query = new Query(Criteria.where("userId").is(userId));
        //2.查询数据总条数
        long count = mongoTemplate.count(query, Movement.class);
        //3.设置分页条件和排序
        query.skip((page - 1) * pageSize)
                .limit(pageSize)
                .with(Sort.by(Sort.Order.desc("created")));
        //4.查询当前页的记录,根据分页查询
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        //5.返回结果
        return new PageResult(page,pageSize, (int) count,list);
    }

    //查询动态不返回总记录数
    @Override
    public List<Movement> findFriendsMovements(Long userId, Integer page, Integer pageSize) {
        //1.查询时间线表获取可以查看的动态id
        Query query = Query.query(Criteria.where("friendId").is(userId));
        query.skip((page - 1)*pageSize)
                .limit(pageSize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> timeLineList = mongoTemplate.find(query, MovementTimeLine.class);
        List<ObjectId> movementIds = timeLineList.stream().map(MovementTimeLine::getMovementId).collect(Collectors.toList());
        //2.查询动态表获取动态信息
        Query movementQuery = Query.query(Criteria.where("id").in(movementIds)).with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movementList = mongoTemplate.find(movementQuery, Movement.class);
        return movementList;
    }


    //当查询推荐信息时没有推荐信息 随机选取十条动态
    @Override
    public List<Movement> randomMovements(int count) {
        //使用MongoDB的统计功能 获取十条动态
        //1.创建统计查询
        TypedAggregation<?> aggregation = Aggregation.newAggregation(Movement.class,Aggregation.sample(count));
        //2.执行统计
        AggregationResults<Movement> aggregate = mongoTemplate.aggregate(aggregation, Movement.class);
        //返回结果
        return aggregate.getMappedResults();
    }

    //根据pids查询推荐的动态信息
    @Override
    public List<Movement> getMovementsByPid(List<Long> pids) {
        //声明查询条件
        Query query =Query.query(Criteria.where("pid").in(pids));
        //执行查询
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        return movementList;
    }

    //根据动态id查询动态信息
    @Override
    public Movement findById(String movementId) {
        return mongoTemplate.findById(new ObjectId(movementId),Movement.class);
    }

    //根据uid和状态查询数据并分页
    @Override
    public PageResult findPage(Integer page, Integer pagesize, Long uid, Integer state) {
        Criteria criteria = Criteria.where("userId").is(uid);
        if (state != null){
            criteria.and("state").is(state);
        }
        Query query = Query.query(criteria);
        long count = mongoTemplate.count(query, Movement.class);
        query.skip((page-1)*pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize, (int) count,movementList);
    }

    //根据动态Id修改审核状态
    @Override
    public void updateState(String movementId, int state) {
        mongoTemplate.updateFirst(
                Query.query(Criteria.where("id").is(new ObjectId(movementId))), Update.update("state",state),Movement.class);
    }
}
